class FurnitureLogisticStat < ActiveRecord::Base

  STORED_COUNT = 'entered_count - sold_count'

  belongs_to :dept
  belongs_to :furniture
  
  scope :spots_orderedable, where('stored_count > ordered_count')
#
#  def self.stored_count_by_furniture_id(furniture_id)
#    sum( :stored_count, :conditions => [
#      'furniture_id = ?', furniture_id
#    ])
#  end
  
  # 重置入库数
  def reset_entered_count!    
    update_attribute :entered_count, EnterItem.where(:furniture_logistic_stat_id => id).sum(:entered_count)
  end
  
  # 重置已预订数
  def reset_ordered_count!    
    self.ordered_count = FurnitureLogisticStatOrderItem.where(:furniture_logistic_stat_id => id).sum(:ordered_count)
    save(:validate => false)
  end
  
  # 重置售出数
  def reset_sold_count!
    update_attribute :sold_count, FurnitureLogisticStatOrderItem.where("furniture_logistic_stat_id = ?",id).sum(:installed_count)
  end

  # 现货可预订数
  def spots_orderedable_count(args = { :order_item_id => 'none'})
    if args[:order_item_id] == 'none' or args[:order_item_id].nil?
      stored_count - ordered_count
    else
      logger.debug "order_item_id is #{args[:order_item_id]} #{stat_order_item_by_order_item_id(args[:order_item_id]).try(:ordered_count) || 0 } "
      stored_count - ordered_count + (stat_order_item_by_order_item_id(args[:order_item_id]).try(:ordered_count) || 0) 
    end
  end

  # 库存数
  def stored_count
    entered_count - sold_count
  end
  
  # 相关联的 stat_order_item 
  def stat_order_item_by_order_item_id(order_item_id)    
    FurnitureLogisticStatOrderItem.where(
      :furniture_logistic_stat_id => id,
      :order_item_id => order_item_id
    ).first
  end
end
